package com.superme.filemanager.controller;

import com.superme.common.beans.Result;
import com.superme.filemanager.service.MediaService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 描述: 媒资管理前端控制器
 * 作者: yanruizhi
 * 时间: 2023/10/31 10:06
 */
@RestController
@RequestMapping("media")
public class MediaController {

    @Resource
    private MediaService mediaService;

    /**
     * 保存媒资信息
     * @param files 文件列表
     */
    @PostMapping("save")
    public Integer saveMedia(List<MultipartFile> files) {
        return mediaService.saveMedia(files);
    }

    @PostMapping("/uploadImg")
    public Result<String> upload(MultipartFile file, HttpServletRequest request) {

        String subPath = "\\upload\\Img\\";
        String basePath = "C:\\Users\\43128\\Desktop\\file";
        String path = "";
        String vpath = "";
        String fileType = "";
        Map<String, Object> resultPath = saveFile(file, basePath + subPath, request);
        path = resultPath.get("path").toString();
        fileType = resultPath.get("fileType").toString();
        vpath = "/statics/upload/" + "Img" + "/" + fileType + "/" + new File(path).getName();

        return Result.OK("上传成功", vpath);
    }

    public static Map<String, Object> saveFile(MultipartFile file, String webFileUrl, HttpServletRequest request) {
        System.out.println();
        String realPath, rootPath = webFileUrl;

        if (webFileUrl.equals("")) {
            //设置主路径
            realPath = request.getServletContext().getRealPath("");
            //将路径设置到当前项目同级，并创建upload文件夹
            rootPath = new File(realPath).getParent() + "\\upload\\";
        }
        //组合文件名
        String filename = System.currentTimeMillis() + "_" + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("\\") + 1);
        //获取文件后缀
        String extension = "." + FilenameUtils.getExtension(filename);
        //生成新的文件名
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + extension;

        // 区分上传文件是图片还是视频
        String fileType;
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(filename);
        if (contentTypeFor == null) {
            fileType = "video";
            rootPath = rootPath + "\\" + fileType + "\\";
        } else {
            fileType = "image";
            rootPath = rootPath + "\\" + fileType + "\\";
        }

        String filePath = rootPath + newFileName;
        File localFile = new File(filePath);

        // 检测是否存在目录，不存在则创建
        if (!localFile.getParentFile().exists()) {
            localFile.getParentFile().mkdirs();
        }
        try {
            //保存文件
            file.transferTo(localFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map<String, Object> result = new HashMap<>();
        result.put("path", localFile.getAbsolutePath());
        result.put("fileType", fileType);
        //返回文件的绝对路径
        return result;
    }

}
